//封装购物车模块

import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { useUserStore } from './user'
import { addCartAPI, findNewCartListAPI, deleteCartListAPI } from '@/apis/cart'


export const useCartStore = defineStore('cart', () => {
    const cartList = ref([])
    //购物车的总金额
    const totalPrice = computed(() => cartList.value.reduce((prev, cur) => prev + cur.count * cur.price, 0))
    //判断是否登录
    const userStore = useUserStore()
    const isLogin = computed(() => userStore.userInfo.token)
    //选中的数量
    const selectedCount = computed(() => cartList.value.filter((item) => item.selected))
    //选中的总价格
    const totalAmount = computed(() => cartList.value.filter((item) => item.selected).reduce((prev, cur) => prev + cur.count * cur.price, 0))
    //是否全选   every :遍历数组的每一项,如果有有一项不满足条件,则表达式返回false,剩余的项将不会再执行检测,如果遍历完数组后每一项都符合条,则返回true
    const isAll = computed(() => cartList.value.every((item) => item.selected))

    //更新购物车
    const update = async ()=>{
        const res = await findNewCartListAPI()
        cartList.value = res.result
    }

    //添加购物车操作
    const addCart = async (goods, count) => {
        if (isLogin.value) {
            //登入之后的逻辑
            const { skuId, count } = goods
            await addCartAPI({ skuId, count })
            update()
        } else {
            const item = cartList.value.find((item) => goods.skuId === item.skuId)
            if (item) {
                //已添加过,count+1
                item.count += count
            } else {
                //未添加,直接push
                cartList.value.push(goods)
            }
        }

    }
    //删除购物车操作
    const delCart = async (skuId) => {
        // 思路:
        if (isLogin.value) {
            await deleteCartListAPI([skuId])
            //覆盖原有数据
            update()
        } else {
            // 1.根据删除项的下标值 -splice
            const index = cartList.value.findIndex((item) => skuId === item.skuId)
            cartList.value.splice(index, 1)
            // 2.使用数组过滤方法 -filter
            // cartList.value = cartList.value.filter((item)=>skuId === item.skuId)  
        }
    }
    //单选功能
    const signChecked = (skuId, selected) => {
        const item = cartList.value.find((item) => item.skuId === skuId)
        item.selected = selected
    }

    //清空购物车
    const clearList = ()=>{
        cartList.value = []
    }

    //全选功能
    const selectedAll = (selected) => {
        cartList.value.forEach((item) => item.selected = selected)
    }

    return {
        cartList,
        totalPrice,
        isAll,
        selectedCount,
        totalAmount,
        addCart,
        delCart,
        signChecked,
        selectedAll,
        clearList,
        update
    }
}, {
    persist: true,
})